package com.cityfood.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cityfood.common.pojo.CityFoodResult;
import com.cityfood.common.pojo.OrderTradeStatus;
import com.cityfood.common.utils.JsonUtils;
import com.cityfood.pojo.CfCardDefault;
import com.cityfood.pojo.CfCardType;
import com.cityfood.pojo.CfOrder;
import com.cityfood.pojo.CfProduct;
import com.cityfood.pojo.CfProductSpecs;
import com.cityfood.pojo.CfCard;
import com.cityfood.service.CardDefaultService;
import com.cityfood.service.CardService;
import com.cityfood.service.CardTypeService;
import com.cityfood.service.OrderService;
import com.cityfood.service.ProductService;
import com.cityfood.service.ProductSpecsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Controller
public class CardController {

	@Autowired
	private CardService cardService;
	
	@Autowired
	private CardTypeService typeService;
	
	@Autowired
	private CardDefaultService defaultService;
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private ProductService productService;
	
	@Autowired
	private ProductSpecsService specsService;
	
	/**
	 * 
	 */
	@RequestMapping(value="/cards/{id}",method=RequestMethod.GET)
	@ResponseBody
	public CityFoodResult getCard(@PathVariable Integer id){
		CityFoodResult cityFoodResult = new CityFoodResult();
		CfCard card = cardService.selectCardById(id);
		if (card!=null) {
			CfOrder order = orderService.getOrder(card.getOrderId());
			Map<String,Object> mp = new LinkedHashMap<>();
			mp.put("orderId", order.getId());
			mp.put("imgUrl", card.getImages());
			mp.put("vedioUrl", card.getVideos());
			mp.put("words", card.getWords());
			mp.put("giveName", card.getGiverName());
			mp.put("giveTime", card.getGiveTime());
			mp.put("Recipient", order.getConsignee());
			mp.put("RecipientPhone", order.getPhone());
			mp.put("RecipientAddress", order.getAddress());
			
			Map<String,Object> productMap = JsonUtils.jsonToMap(order.getProductSpecsIds());
			List<Map<String,Object>> ls = new ArrayList<>();
			for (String specsId : productMap.keySet()) {
				Map<String,Object> ms = new LinkedHashMap<>();
				CfProductSpecs productSpecs = specsService.getProductSpecsBySpecsId(Integer.parseInt(specsId));
				ms.put("id", productSpecs.getId());
				CfProduct product = productService.getProductByProductId(productSpecs.getProductId());
				ms.put("prpductId", product.getId());
				ms.put("productName", product.getName());
				ms.put("productPic", product.getMainImage());
				ms.put("price", productSpecs.getPrice());
				ms.put("num", productMap.get(specsId));
				
				Map<String,String> tasteMap = (Map<String,String>)JsonUtils.jsonToMap(productSpecs.getProductSpecs());
				
				String taste = "";
				for (String str : tasteMap.values()) {
					taste=str+"/"+taste;
				}
				taste=taste.substring(0, taste.length()-1);
				ms.put("attrs", taste);
				ls.add(ms);
			}
			mp.put("products", ls);
			
			cityFoodResult.setCode(200);
			cityFoodResult.setMsg("查询卡片成功");
			cityFoodResult.setData(mp);
			return cityFoodResult;
		}
		cityFoodResult.setCode(201);
		cityFoodResult.setMsg("系统错误");
		cityFoodResult.setData("");
		return cityFoodResult;
	}
	
	@RequestMapping(value="/cards",method=RequestMethod.POST)
	@ResponseBody
	public CityFoodResult addCard (
			@RequestParam int userId,
			@RequestParam int orderId,
			@RequestParam(defaultValue="") String imgUrl,
			@RequestParam(defaultValue="") String vedioUrl,
			@RequestParam(defaultValue="") String reciverName,
			@RequestParam String words,
			@RequestParam String giveName,
			@RequestParam String giveTime) throws ParseException{
		CityFoodResult cityFoodResult = new CityFoodResult();
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		CfCard  card = new CfCard();
		card.setUserId(userId);
		card.setOrderId(orderId);
		card.setImages(imgUrl);
		card.setVideos(vedioUrl);
		card.setReciverName(reciverName);
		card.setWords(words);
		card.setGiverName(giveName);
		card.setGiveTime(sd.parse(giveTime));
		
		int res = cardService.insertCard(card);
		
		if(res == 1){
			CfOrder order  = orderService.getOrder(orderId);
			order.setTradeStatus((byte)OrderTradeStatus.WAIT_PRESENT.getStatus());
			orderService.updateOrderStatus(order);
			
			CfCard newCard = cardService.selectCardByOrderId(orderId);
			
			cityFoodResult.setCode(200);
			cityFoodResult.setData(newCard.getId()); //返回新增CardID
			cityFoodResult.setMsg("新增贺卡成功");
		}else{
			cityFoodResult.setCode(500);
			cityFoodResult.setData(false);
			cityFoodResult.setMsg("服务器错误");
		}
		
		return cityFoodResult;
	}
	
	
	//TODO:takeCard 收礼人收礼：订单状态改已领取
	@RequestMapping(value="/cards/take",method=RequestMethod.PUT)
	@ResponseBody
	public CityFoodResult takeCard (@RequestParam Integer cardId){
		CityFoodResult cityFoodResult = new CityFoodResult();
		CfCard card = cardService.selectCardById(cardId);
		CfOrder order = orderService.getOrder(card.getOrderId());
		order.setTradeStatus((byte)7);
		int i = orderService.updateOrderStatus(order);
		if (i>0) {
			cityFoodResult.setCode(200);
			cityFoodResult.setMsg("收礼成功");
			cityFoodResult.setData(true);
			return cityFoodResult;
		}
		cityFoodResult.setCode(201);
		cityFoodResult.setMsg("系统错误");
		cityFoodResult.setData(false);
		return cityFoodResult;
	}
	
	
	
	
	//后台管理------------------------------------------------------------------------------------------------

	/**
	 * 查询卡片类型，currentPage页码，默认为1
	 */
	@RequestMapping(value="/manage/cardTypes",method=RequestMethod.GET)
	@ResponseBody
	public CityFoodResult getCardType(@RequestParam(defaultValue="1") Integer currentPage){
		CityFoodResult cityFoodResult = new CityFoodResult();
		Map<String,Object> ms = new LinkedHashMap<>();
		//返回所有cardType
		if(currentPage == 0){
			List<CfCardType> list = typeService.selectAllCardType();
			if(list.size() > 0){
				ms.put("total", list.size());
				ms.put("cardTypes", list);
				cityFoodResult.setCode(200);
				cityFoodResult.setMsg("查询所有卡片类型成功");
				cityFoodResult.setData(ms);
				return cityFoodResult;
			}
		}
		//分页显示所有cardType
		PageInfo<CfCardType> typeList = typeService.selectCardType(currentPage, 20);
		if (typeList.getList().size()>0) {
			
			
			ms.put("total", typeList.getTotal());
			ms.put("cardTypes", typeList.getList());
			
			cityFoodResult.setCode(200);
			cityFoodResult.setMsg("查询卡片类型成功");
			cityFoodResult.setData(ms);
			return cityFoodResult;
		}
		cityFoodResult.setCode(201);
		cityFoodResult.setMsg("查询卡片类型失败");
		cityFoodResult.setData("");
		return cityFoodResult;
	}
	
	/**
	 * 添加卡片类型，name类型名称，details类型详情介绍
	 */
	@RequestMapping(value="/manage/cardTypes",method=RequestMethod.POST)
	@ResponseBody
	public CityFoodResult insertCardType(@RequestBody Map<String,Object> map){
		
		CityFoodResult cityFoodResult = new CityFoodResult();
		
		String name = (String)map.get("name");
		String details = (String)map.get("details");
		
		CfCardType cardType = new CfCardType();
		cardType.setName(name);
		cardType.setDetails(details);
		int i = typeService.insertCardType(cardType);
		if (i>0) {
			cityFoodResult.setCode(200);
			cityFoodResult.setMsg("添加卡片类型成功");
			cityFoodResult.setData(true);
			return cityFoodResult;
		}
		cityFoodResult.setCode(201);
		cityFoodResult.setMsg("添加卡片类型失败");
		cityFoodResult.setData(false);
		return cityFoodResult;
	}
	
	/**
	 * 修改卡片类型
	 */
	@RequestMapping(value="/manage/cardTypes",method=RequestMethod.PUT)
	@ResponseBody
	public CityFoodResult updateCardType(@RequestBody Map<String,Object> map){
		
		CityFoodResult cityFoodResult = new CityFoodResult();
		
		Integer id = Integer.parseInt(map.get("id").toString());
		String name = (String)map.get("name");
		String details = (String)map.get("details");
		
		CfCardType cardType = new CfCardType();
		cardType.setId(id);
		cardType.setName(name);
		cardType.setDetails(details);
		int i = typeService.updateCardType(cardType);
		if (i>0) {
			cityFoodResult.setCode(200);
			cityFoodResult.setMsg("修改卡片类型成功");
			cityFoodResult.setData(true);
			return cityFoodResult;
		}
		cityFoodResult.setCode(201);
		cityFoodResult.setMsg("修改卡片类型失败");
		cityFoodResult.setData(false);
		return cityFoodResult;
	}
	
	/**
	 * 删除卡片，id例如：1
	 */
	@RequestMapping(value="/manage/cardTypes/remove",method=RequestMethod.DELETE)
	@ResponseBody
	public CityFoodResult deleteCardType(@RequestBody Map map){
	    String id = map.get("id").toString();
		CityFoodResult cityFoodResult = new CityFoodResult();
		List<CfCardDefault> defaultList = defaultService.selectCardDefaultByTypeId(Integer.parseInt(id));
		if (defaultList.size()>0) {
			for (CfCardDefault cardDefault : defaultList) {
				int i = defaultService.deleteCardDefault(cardDefault.getId());
				if (i<=0) {
					cityFoodResult.setCode(201);
					cityFoodResult.setMsg("修改卡片类型失败");
					cityFoodResult.setData(false);
					return cityFoodResult;
				}
			}
		}
		int i = typeService.deleteCardType(Integer.parseInt(id));
		if (i>0) {
			cityFoodResult.setCode(200);
			cityFoodResult.setMsg("删除卡片类型成功");
			cityFoodResult.setData(true);
			return cityFoodResult;
		}
		cityFoodResult.setCode(201);
		cityFoodResult.setMsg("删除卡片类型失败");
		cityFoodResult.setData(false);
		return cityFoodResult;
	}
	
	/**
	 * 批量删除卡片类型，ids例如：1,2,3
	 */
	@RequestMapping(value="/manage/cardTypes/batchremove",method=RequestMethod.DELETE)
	@ResponseBody
	public CityFoodResult deleteCardTypes(@RequestBody Map map){
	    String ids = map.get("ids").toString();
		CityFoodResult cityFoodResult = new CityFoodResult();
		String[] strIds = ids.split(",");
		
		for (String typeId : strIds) {
			List<CfCardDefault> defaultList = defaultService.selectCardDefaultByTypeId(Integer.parseInt(typeId));
			if (defaultList.size()>0) {
				for (CfCardDefault cardDefault : defaultList) {
					int i = defaultService.deleteCardDefault(cardDefault.getId());
					if (i<=0) {
						cityFoodResult.setCode(201);
						cityFoodResult.setMsg("删除卡片类型失败");
						cityFoodResult.setData(false);
						return cityFoodResult;
					}
				}
			}
			int i = typeService.deleteCardType(Integer.parseInt(typeId));
			if (i<=0) {
				cityFoodResult.setCode(201);
				cityFoodResult.setMsg("删除卡片类型失败");
				cityFoodResult.setData(false);
				return cityFoodResult;
			}
		}
		
	
		cityFoodResult.setCode(200);
		cityFoodResult.setMsg("修改卡片类型成功");
		cityFoodResult.setData(true);
		return cityFoodResult;
	}
	
	
	/**
	 * 查询卡片，currentPage页码，默认为1，typeId，卡片类型id，默认为0查询全部
	 */
	@RequestMapping(value="/manage/cardDefaults",method=RequestMethod.GET)
	@ResponseBody
	public CityFoodResult getCardDefault(@RequestParam(defaultValue="0") Integer typeId,
											@RequestParam(defaultValue="1") Integer currentPage){
		CityFoodResult cityFoodResult = new CityFoodResult();
		
		List<Map<String,Object>> ls = new ArrayList<>();
		
		//分页显示所有cardDefault
		List<CfCardDefault> cardDefaultList = new ArrayList<>();
		//设置分页的页数和行数
		PageHelper.startPage(currentPage, 20);
		if (typeId==0) {
			cardDefaultList = defaultService.selectCardDefault();
		}else{
			cardDefaultList = defaultService.selectCardDefaultByTypeId(typeId);
		}
		//5.获取分页信息
		PageInfo<CfCardDefault> cardDefaultListPage = new PageInfo<>(cardDefaultList);
		if (cardDefaultList==null) {
			cityFoodResult.setCode(201);
			cityFoodResult.setMsg("查询卡片列表失败");
			cityFoodResult.setData("");
			return cityFoodResult;
		}
		for (CfCardDefault cardDefault : cardDefaultListPage.getList()) {
			Map<String,Object> mp = new LinkedHashMap<>();
			mp.put("id", cardDefault.getId());
			CfCardType cardType = typeService.selectCardTypeById(cardDefault.getTypeId());
			mp.put("typeId", cardDefault.getTypeId());
			mp.put("typeName", cardType.getName());
			mp.put("url", cardDefault.getUrl());
			mp.put("description", cardDefault.getDescription());
			ls.add(mp);
		}
		
		if (ls.size()>0) {
			
			Map<String,Object> ms = new LinkedHashMap<>();
			ms.put("total", cardDefaultListPage.getTotal());
			ms.put("cardDefaults", ls);
			
			cityFoodResult.setCode(200);
			cityFoodResult.setMsg("查询卡片列表成功");
			cityFoodResult.setData(ms);
			return cityFoodResult;
		}
		cityFoodResult.setCode(201);
		cityFoodResult.setMsg("查询卡片列表失败");
		cityFoodResult.setData("");
		return cityFoodResult;
	}
	
	/**
	 * 添加卡片
	 */
	@RequestMapping(value="/manage/cardDefaults",method=RequestMethod.POST)
	@ResponseBody
	public CityFoodResult insertCardDefault(@RequestBody Map<String,Object> map){
		
		CityFoodResult cityFoodResult = new CityFoodResult();
		
		Integer typeId = Integer.parseInt(map.get("typeId").toString());
		String url = (String)map.get("url");
		String description = (String)map.get("description");
		
		CfCardDefault cardDefault=new CfCardDefault();
		cardDefault.setTypeId(typeId);
		cardDefault.setUrl(url);
		cardDefault.setDescription(description);
		int i = defaultService.insertCardDefault(cardDefault);
		if (i>0) {
			cityFoodResult.setCode(200);
			cityFoodResult.setMsg("添加卡片成功");
			cityFoodResult.setData(true);
			return cityFoodResult;
		}
		cityFoodResult.setCode(201);
		cityFoodResult.setMsg("添加卡片失败");
		cityFoodResult.setData(false);
		return cityFoodResult;
	}
	
	/**
	 * 修改卡片
	 */
	@RequestMapping(value="/manage/cardDefaults",method=RequestMethod.PUT)
	@ResponseBody
	public CityFoodResult updateCardDefault(@RequestBody Map<String,Object> map){		
		CityFoodResult cityFoodResult = new CityFoodResult();
		
		Integer id = Integer.parseInt(map.get("id").toString());
		Integer typeId = Integer.parseInt(map.get("typeId").toString());
		String url = (String)map.get("url");
		String description = (String)map.get("description");
		
		CfCardDefault cardDefault=new CfCardDefault();
		cardDefault.setId(id);
		cardDefault.setTypeId(typeId);
		cardDefault.setUrl(url);
		cardDefault.setDescription(description);
		int i = defaultService.updateCardDefault(cardDefault);
		if (i>0) {
			cityFoodResult.setCode(200);
			cityFoodResult.setMsg("修改卡片成功");
			cityFoodResult.setData(true);
			return cityFoodResult;
		}
		cityFoodResult.setCode(201);
		cityFoodResult.setMsg("修改卡片失败");
		cityFoodResult.setData(false);
		return cityFoodResult;
	}
	
	/**
	 * 删除卡片，id例如：1
	 */
	@RequestMapping(value="/manage/cardDefaults/remove",method=RequestMethod.DELETE)
	@ResponseBody
	public CityFoodResult deleteCardDefault(@RequestBody Map map){
	    String id = map.get("id").toString();
		CityFoodResult cityFoodResult = new CityFoodResult();
		
		int i = defaultService.deleteCardDefault(Integer.parseInt(id));
		if (i>0) {
			cityFoodResult.setCode(200);
			cityFoodResult.setMsg("删除卡片成功");
			cityFoodResult.setData(true);
			return cityFoodResult;
		}
		cityFoodResult.setCode(201);
		cityFoodResult.setMsg("删除卡片失败");
		cityFoodResult.setData(false);
		return cityFoodResult;
	}
	
	/**
	 * 批量删除卡片，ids例如：1,2,3
	 */
	@RequestMapping(value="/manage/cardDefaults/batchremove",method=RequestMethod.DELETE)
	@ResponseBody
	public CityFoodResult deleteCardDefaults(@RequestBody Map map){
	    String ids = map.get("ids").toString();
		CityFoodResult cityFoodResult = new CityFoodResult();
		String[] strIds = ids.split(",");
		
		for (String id : strIds) {
			int i = defaultService.deleteCardDefault(Integer.parseInt(id));
			if (i<=0) {
				cityFoodResult.setCode(201);
				cityFoodResult.setMsg("删除卡片类型失败");
				cityFoodResult.setData(false);
				return cityFoodResult;
			}
		}
		
		cityFoodResult.setCode(200);
		cityFoodResult.setMsg("修改卡片类型成功");
		cityFoodResult.setData(true);
		return cityFoodResult;
	}
	
	
}
